package com.wbase.permission.request

import android.annotation.TargetApi
import android.content.pm.PackageManager
import android.os.Build
import android.os.Bundle
import androidx.fragment.app.Fragment


/**
 * 权限检查Fragment
 *
 * @author wangheng
 */
class PermissionRequestFragment: Fragment() {

    companion object{
        private const val CODE_REQUEST_PERMISSION = 1001
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        retainInstance = true
    }

    private var mCallback: (isAllGranted: Boolean,
                            isAllCantShow: Boolean,
                            deniedList: ArrayList<String>,
                            list: ArrayList<Permission>) -> Unit = { _, _, _, _ -> }

    fun requestPermissions(permissions: ArrayList<String>,
                           callback: (isAllGranted: Boolean,
                                isAllCantShow: Boolean,
                                deniedList: ArrayList<String>,
                                list: ArrayList<Permission>) -> Unit){
        // 检查如果版本低于6.0，则直接返回所有的权限都被赋予
        if(!needCheckPermission()){
            val allGranted = true
            val allCantShow = false

            val resultList = ArrayList<Permission>()
            permissions.forEach {
                resultList.add(Permission(it, true, true))
            }

            callback(allGranted,allCantShow, ArrayList(),resultList)
            return
        }

        // 判断列表所有的权限是否全部都已经赋予，如果都已经赋予，则直接诶返回
//        var allGranted = true
//        val resultList = ArrayList<Permission>()
//        val deniedList = ArrayList<String>()
//        permissions.forEach {
//            val granted = isGranted(it)
//            if(!granted){
//                allGranted = false
//                deniedList.add(it)
//            }
//
//            resultList.add(Permission(it, granted, shouldShow))
//        }
//        Logger.i("wangheng",">>>>>>all granted:$allGranted,$allCantShow")
//        if(allGranted){
//            callback(allGranted,false, deniedList,resultList)
//            return
//        }


        // 请求权限
        this.mCallback = callback
        val array = Array(permissions.size){ permissions[it] }
        requestPermissions(array, CODE_REQUEST_PERMISSION)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode != CODE_REQUEST_PERMISSION){
            return
        }

        val resultList = ArrayList<Permission>(permissions.size)
        var isAllGranted = true
        var isAllCantShow = true
        val deniedList = ArrayList<String>()

        permissions.forEachIndexed{index,permission ->
            // 是否已经赋予权限
            val granted = grantResults[index] == PackageManager.PERMISSION_GRANTED

            if(!granted){       // 如果有任何一个没有赋予的权限，则把"全部都赋予"变量置为false
                isAllGranted = false
                deniedList.add(permission)
            }

            // 能否再次显示
            val shouldShow = shouldShowRequestPermissionRationale(permission)

            if(shouldShow){     // 有任何一个可以再次显示，都把"全部不可以再次显示"变量设置成false
                isAllCantShow = false
            }

            resultList.add(
                Permission(permission, granted, shouldShow))
        }

        mCallback(isAllGranted,isAllCantShow,deniedList,resultList)

    }

    /**
     * 是否需要请求权限(只有大于或者等于SDK 23版本才需要请求权限)
     */
    private fun needCheckPermission(): Boolean {
        return Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun isGranted(permission: String): Boolean {
        val fragmentActivity = activity
            ?: throw IllegalStateException("This fragment must be attached to an activity.")
        return fragmentActivity.checkSelfPermission(permission) == PackageManager.PERMISSION_GRANTED
    }

    @TargetApi(Build.VERSION_CODES.M)
    fun isRevoked(permission: String): Boolean {
        val fragmentActivity = activity
            ?: throw IllegalStateException("This fragment must be attached to an activity.")
        return fragmentActivity.packageManager
            .isPermissionRevokedByPolicy(permission, fragmentActivity.packageName)
    }

}